using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QLHXNK.BusinessLogic;

namespace QLHXNK.Forms
{
    public partial class NewFrmDanhMucHangHoa : Form
    {
        int action = -1;
        private Item item;
        private Item[] arrItemExist = new Item[100];
        private Item[] arrItemDeleted = new Item[100];
        DataTable dtItemExist;
        private int ItemExistCount = 0;
        private int ItemDeletedCount = 0;
        private bool isDeleteRow = false;
        private int existRow = -1;

        public NewFrmDanhMucHangHoa()
        {
            InitializeComponent();
            this.CenterToScreen();
        }

        private void NewFrmDanhMucHangHoa_Load(object sender, EventArgs e)
        {
            dtItemExist = Item.ListItem();
            dgvDanhMucHangHoa.DataSource = dtItemExist;
            for (int i = 0; i < dtItemExist.Rows.Count; i++)
            {
                arrItemExist[ItemExistCount] = new Item(Int32.Parse(dtItemExist.Rows[i]["ID"].ToString()),
                                                    dtItemExist.Rows[i]["item_code"].ToString(),
                                                    dtItemExist.Rows[i]["item_name"].ToString(),
                                                    dtItemExist.Rows[i]["item_specs"].ToString(),
                                                    dtItemExist.Rows[i]["item_unit"].ToString(),
                                                    dtItemExist.Rows[i]["remark"].ToString());
                ItemExistCount++;
            }
            lbKetQua.Visible = false;
        }

        private void dgvDanhMucHangHoa_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            lbKetQua.Visible = false;
            if (e.RowIndex != -1)
            {
                if (dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["ID"].Value!=null&&dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["ID"].Value.ToString() != "")
                    action = 2;
                else
                    action = 0;
            }
        }

        private void dgvDanhMucHangHoa_KeyDown(object sender, KeyEventArgs e)
        {
            lbKetQua.Visible = false;
            if (e.KeyValue == 46 && ItemDeletedCount != 0)
            {
                dgvDanhMucHangHoa.AllowUserToDeleteRows = true;
                DialogResult result = DialogResult;
                if (ItemDeletedCount == 1)
                    result = MessageBox.Show("Bạn muốn xoá hàng này", "Xoá", MessageBoxButtons.YesNo);
                if (ItemDeletedCount > 1)
                    result = MessageBox.Show("Bạn muốn xoá danh sách hàng bạn chọn", "Xoá", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    String note = "";
                    isDeleteRow = true;
                    for (int i = 0; i < ItemDeletedCount; i++)
                    {
                        if (Item.GetItemInImportNote(arrItemDeleted[i].ID).Rows.Count == 0)
                        {
                            int kq = arrItemDeleted[i].DeleteItem();
                            if (kq == 1)
                                DeleteArrItemExist(arrItemDeleted[i].ID);
                        }
                        else
                            note = note + "--" + arrItemDeleted[i].Name;
                    }
                    ItemDeletedCount = 0;
                    if (note != "")
                        MessageBox.Show("Không thể xoá những hàng:" + note);
                }
                else
                    dgvDanhMucHangHoa.AllowUserToDeleteRows = false;
            }
            if (e.KeyValue == 27)
                this.Close();
        }

        private void dgvDanhMucHangHoa_SelectionChanged(object sender, EventArgs e)
        {
            if (existRow != -1)
            {
                dgvDanhMucHangHoa.Rows[existRow].Cells["MaHang"].Value = null;
                dgvDanhMucHangHoa.Rows[existRow].Cells["TenHang"].Value = null;
                dgvDanhMucHangHoa.Rows[existRow].Cells["QuyCach"].Value = null;
                dgvDanhMucHangHoa.Rows[existRow].Cells["DVT"].Value = null;
                dgvDanhMucHangHoa.Rows[existRow].Cells["GhiChu"].Value = null;
                existRow = -1;
            }
            DataGridViewSelectedRowCollection rows = dgvDanhMucHangHoa.SelectedRows;
            if (rows.Count > 0)
            {
                ItemDeletedCount = 0;
                for (int i = 0; i < rows.Count; i++)
                {
                    DataGridViewRow row = rows[i];
                    if (row.Cells["ID"].Value != null && row.Cells["ID"].Value.ToString() != "")
                    {
                        arrItemDeleted[ItemDeletedCount++] = new Item(Int32.Parse(row.Cells["ID"].Value.ToString()),
                                        row.Cells["MaHang"].Value.ToString(),
                                        row.Cells["TenHang"].Value.ToString(),
                                        row.Cells["QuyCach"].Value.ToString(),
                                        row.Cells["DVT"].Value.ToString(),
                                        row.Cells["GhiChu"].Value.ToString());
                    }
                }
            }
        }

        private void dgvDanhMucHangHoa_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            lbKetQua.Visible = false;
            String itemCode = "";
            String itemName = "";
            String itemSpecs = "";
            String itemUnit = "";
            String remark = "";
            if (dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["MaHang"].Value != null)
                itemCode = dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["MaHang"].Value.ToString().Trim();
            if (dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["TenHang"].Value != null)
                itemName = dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["TenHang"].Value.ToString().Trim();
            if (dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["QuyCach"].Value != null)
                itemSpecs = dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["QuyCach"].Value.ToString().Trim();
            if (dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["DVT"].Value != null)
                itemUnit = dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["DVT"].Value.ToString().Trim();
            if (dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["GhiChu"].Value != null)
                remark = dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["GhiChu"].Value.ToString().Trim();

            if (e.RowIndex != -1 && action == 0)
            {
                if (itemCode != "" && itemName != "")
                {
                    DataTable dtItem = Item.GetItemByName(itemName);
                    if (dtItem.Rows.Count > 0)
                    {
                        MessageBox.Show("Đã có mặt hàng này trong danh sách !!!");
                        existRow = e.RowIndex;
                        action = -1;
                        return;
                    }
                    item = Item.CreateItem(itemCode, itemName, itemSpecs, itemUnit, remark);

                    if (item == null)
                        MessageBox.Show("Dữ liệu nhập vào không hơp hợp lệ ");
                    else
                    {
                        arrItemExist[ItemExistCount++] = item;
                        ShowNote("Thêm thành công mặt hàng -" + item.Name + "",Color.Blue);
                    }
                    action = -1;
                }
                else
                {
                    MessageBox.Show("Hảy nhập đầy đủ thông tin cho mặt hàng");
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["MaHang"].Value = "";
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["TenHang"].Value = "";
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["QuyCach"].Value = "";
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["DVT"].Value = "";
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["GhiChu"].Value = "";
                    action = -1;
                    return;
                }
            }
            if (e.RowIndex != -1 && action == 2)
            {
                int i;
                for (i = 0; i < ItemExistCount; i++)
                {
                    if (arrItemExist[i].ID.ToString() == dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["ID"].Value.ToString())
                        break;
                }
                if (itemCode != "" && itemName != "")
                {
                    for (int j = 0; j < dgvDanhMucHangHoa.Rows.Count; j++)
                        if (j != e.RowIndex && dgvDanhMucHangHoa.Rows[j].Cells["TenHang"].Value != null && itemName == dgvDanhMucHangHoa.Rows[j].Cells["TenHang"].Value.ToString())
                        {
                            MessageBox.Show("Đã có mặt hàng với tên này trong danh sách !!!");
                            dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["MaHang"].Value = arrItemExist[i].Code;
                            dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["TenHang"].Value = arrItemExist[i].Name;
                            dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["QuyCach"].Value = arrItemExist[i].ItemSpecs;
                            dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["DVT"].Value = arrItemExist[i].ItemUnit;
                            dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["GhiChu"].Value = arrItemExist[i].Remark;
                            action = -1;
                            return;
                        }

                    try
                    {
                        int kq= arrItemExist[i].UpdateItem(itemCode, itemName, itemSpecs, itemUnit, remark);
                        if (kq == 1)
                            ShowNote("Đã cập nhật thông tin cho mặt hàng",Color.Blue);
                        action = -1;
                    }
                    catch { action = -1; }

                }
                else
                {
                    MessageBox.Show("Chưa cập nhật thông tin vì không đủ thông tin cho mặt hàng");
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["MaHang"].Value = arrItemExist[i].Code;
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["TenHang"].Value = arrItemExist[i].Name;
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["QuyCach"].Value = arrItemExist[i].ItemSpecs;
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["DVT"].Value = arrItemExist[i].ItemUnit;
                    dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["GhiChu"].Value = arrItemExist[i].Remark;
                    action = -1;
                }

            }
        }

        private void dgvDanhMucHangHoa_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            if (isDeleteRow == true)
            {
                isDeleteRow = false;
                dgvDanhMucHangHoa.DataSource = Item.ListItem();
            }
        }



        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            lbKetQua.Visible = false;
            if (ItemDeletedCount != 0)
            {
                DialogResult result = DialogResult;
                if (ItemDeletedCount == 1)
                    result = MessageBox.Show("Bạn muốn xoá hàng này", "Xoá", MessageBoxButtons.YesNo);
                if (ItemDeletedCount > 1)
                    result = MessageBox.Show("Bạn muốn xoá danh sách hàng bạn chọn", "Xoá", MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    String note = "";
                    isDeleteRow = true;
                    for (int i = 0; i < ItemDeletedCount; i++)
                    {
                        if (Item.GetItemInImportNote(arrItemDeleted[i].ID).Rows.Count == 0)
                        {
                            int kq = arrItemDeleted[i].DeleteItem();
                            if (kq == 1)
                                DeleteArrItemExist(arrItemDeleted[i].ID);
                        }
                        else
                            note = note + "--" + arrItemDeleted[i].Name;
                    }
                    ItemDeletedCount = 0;
                    if (note != "")
                        MessageBox.Show("Không thể xoá những hàng:" + note);
                    dgvDanhMucHangHoa.DataSource = Item.ListItem();
                }
            }
            
        }

        private void DeleteArrItemExist(int ID)
        {
            int i;
            for (i = 0; i < ItemExistCount; i++)
            {
                if (ID == arrItemExist[i].ID)
                {
                    ItemExistCount--;
                    break;
                }
            }
            for (int j = i; j < ItemExistCount; j++)
                arrItemExist[j] = arrItemExist[j + 1];

        }

        private void UpdateIDInRowByCode(Object itemName)
        {
            if (itemName == null)
                itemName = "";
            for (int i = 0; i < dgvDanhMucHangHoa.Rows.Count; i++)
            {
                if (dgvDanhMucHangHoa.Rows[i].Cells["TenHang"].Value != null && dgvDanhMucHangHoa.Rows[i].Cells["TenHang"].Value.ToString() != "")
                    if (dgvDanhMucHangHoa.Rows[i].Cells["TenHang"].Value.ToString() == itemName.ToString())
                        if (dgvDanhMucHangHoa.Rows[i].Cells["ID"].Value == null || dgvDanhMucHangHoa.Rows[i].Cells["ID"].Value.ToString() == "")
                        {
                            DataTable dttmp = Item.GetItemByName(dgvDanhMucHangHoa.Rows[i].Cells["TenHang"].Value.ToString());
                            if (dttmp.Rows.Count > 0)
                                dgvDanhMucHangHoa.Rows[i].Cells["ID"].Value = dttmp.Rows[0]["ID"].ToString();
                            break;
                        }
            }
        }

        private void ShowNote(string note, Color foreColor)
        {
            lbKetQua.Visible = true;
            lbKetQua.ForeColor = foreColor;
            lbKetQua.Text = note;
        }

        private void btnThoat_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 27)
                this.Close();
        }

        private void dgvDanhMucHangHoa_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            UpdateIDInRowByCode(dgvDanhMucHangHoa.Rows[e.RowIndex].Cells["TenHang"].Value);
        }
    }
}